package com.vm.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.vm.commons.VMConst;
import com.vm.fragment.UIHelper;
import com.vm.model.ActiveSoft;
import com.vm.model.Soft;
import com.vm.myview.ViewUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwt.app.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月4日 下午2:18:56]
 * @Version: [v1.0]
 * 
 */
public class ActiveActivity extends Activity {

	protected static final String TAG = "ActiveActivity";

	private List<Soft> listsofts;
	private TextView tv_currentType;
	ImageButton imgbtn_search_back; // 返回按钮
	private RequestQueue mQueue;

	ScrollView mScrollView;
	boolean canRequest = true;
	String name;
	int pageNow = 1;
	LinearLayout found_ll_1;

	String activeType;
	String currentType;

	ViewUtils viewUtils;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.active);
		
		UIHelper.showDialogForLoading(this, "正在加载...", true);

		
		activeType = getIntent().getStringExtra("activeType");
		currentType = getIntent().getStringExtra("currentType");
		init();

		viewUtils = new ViewUtils(this);
		mQueue = MyVolley.getRequestQueue();

		listsofts = new ArrayList<Soft>();

		final String url = VMConst.REQUEST_URL + activeType;
		JsonArrayRequest searchArrayRequest = new JsonArrayRequest(url,
				new Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray arg0) {

						found_ll_1.removeAllViews();
						for (int i = 0; i < arg0.length(); i++) {
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								final ActiveSoft activeSoft = JsonUtils
										.jsonToBean(jsonObject,
												ActiveSoft.class);

								// 判断是活动类型还是软件类型
								if (url.contains("getSoftByType")) {
									System.out.println("判断是活动类型还是软件类型");
									activeSoft.setSoftId(activeSoft.getId());
									activeSoft.setId(null);
								}

								found_ll_1.addView(viewUtils.dyAddView(i,
										activeSoft, 1));

							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						
						UIHelper.hideDialogForLoading();

					}

				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// Log.e(TAG, error.getMessage(), error);
					}
				});

		mQueue.add(searchArrayRequest);

		imgbtn_search_back = (ImageButton) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);

		/**
		 * 跳转到搜索页面
		 */
		ImageView iv_search = (ImageView) findViewById(R.id.iv_search);
		iv_search.setOnClickListener(new OnClickListener
				() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ActiveActivity.this,
						SearchActivity.class);
				startActivityForResult(intent, 10);
			}
		});
	}

	/**
	 * @param currentType
	 */
	private void init() {
		tv_currentType = (TextView) findViewById(R.id.tv_small_category_name);
		tv_currentType.setText(currentType);

		found_ll_1 = (LinearLayout) findViewById(R.id.found_ll_1);
		mScrollView = (ScrollView) findViewById(R.id.scrollview_list);
		mScrollView.setOnTouchListener(new TouchListenerImpl());
	}

	/**
	 * imgbtn_search_back返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// Log.i(TAG, "imgbtn_search_back返回按钮监听");
			onBackPressed();

		}
	};

	/**
	 * 返回按钮监听(手机自带返回按钮)
	 */
	@Override
	public void onBackPressed() {
		// Log.i(TAG, "返回按钮监听(手机自带返回按钮)");
		super.onBackPressed();
		// System.out.println("按下了back键   onBackPressed()");
	}

	/**
	 * listview_listener item监听
	 */
	OnItemClickListener listview_listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			Intent intent = new Intent(ActiveActivity.this,
					DetailActivity.class);
			TextView textView = (TextView) view.findViewById(R.id.tv_softName);
			String softId = textView.getTag().toString();
			intent.putExtra("softId", softId);
			startActivityForResult(intent, 10);

		}
	};

	private class TouchListenerImpl implements OnTouchListener {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			switch (motionEvent.getAction()) {
			case MotionEvent.ACTION_DOWN:

				break;
			case MotionEvent.ACTION_MOVE:
				int scrollY = view.getScrollY();
				int height = view.getHeight();
				int scrollViewMeasuredHeight = mScrollView.getChildAt(0)
						.getMeasuredHeight();
				if (scrollY == 0) {
					System.out.println("滑动到了顶端 view.getScrollY()=" + scrollY);
				}
				if ((scrollY + height) == scrollViewMeasuredHeight) {

					if (canRequest) {
						canRequest = false;
						System.out.print("canRequest:" + canRequest);
						pageNow += 1;
						System.out.print("pageNow:" + pageNow);
						String url = VMConst.REQUEST_URL + activeType;
						if (url.contains("?")) {
							url += "&pageNow=" + pageNow;
						} else {
							url += "?pageNow=" + pageNow;
						}

						final String url2 = url;

						JsonArrayRequest searchArrayRequest = new JsonArrayRequest(
								url2, new Listener<JSONArray>() {
									@Override
									public void onResponse(JSONArray arg0) {

										for (int i = 0; i < arg0.length(); i++) {
											try {
												JSONObject jsonObject = arg0
														.getJSONObject(i);

												final ActiveSoft activeSoft = JsonUtils
														.jsonToBean(
																jsonObject,
																ActiveSoft.class);

												// 判断是活动类型还是软件类型
												if (url2.contains("getSoftByType")) {
													System.out
															.println("判断是活动类型还是软件类型");
													activeSoft
															.setSoftId(activeSoft
																	.getId());
													activeSoft.setId(null);
												}

												LinearLayout linearLayout = viewUtils
														.dyAddView(i,
																activeSoft, 1);
												found_ll_1
														.addView(linearLayout);

											} catch (JSONException e) {
												// TODO Auto-generated catch
												// block
												e.printStackTrace();
											}
										}
										canRequest = true;

									}

								}, new Response.ErrorListener() {
									@Override
									public void onErrorResponse(
											VolleyError error) {
										// Log.e(TAG, error.getMessage(),
										// error);
									}
								});

						mQueue.add(searchArrayRequest);

					}

				}
				break;

			default:
				break;
			}
			return false;
		}

	};

}
